package com.zhangyx.crawler.proxy;

import com.zhangyx.crawler.comm.RedisUtil;
import org.apache.log4j.Logger;

import java.util.List;

public class ProxyPool extends Thread{
    private static Logger log = Logger.getLogger(ProxyPool.class);
    private static final String proxy_pool_key = "proxy_pool_key";

    public static void init() {
        RedisUtil.del(proxy_pool_key);
        ProxyPool proxyPool = new ProxyPool();
        proxyPool.start();
    }

    @Override
    public void run() {
        while (true) {
            try {
                List<ProxyEntity> proxyEntityList = DynamicHandle.getProxy();
                for (ProxyEntity entity : proxyEntityList) {
                    addProxy(entity);
                }
                Thread.sleep(500 * 1);
            }catch (Exception e) {
                log.error(e.getMessage());
            }

        }
    }

    public static void addProxy(ProxyEntity entity) {
        RedisUtil.pushQueueObj(proxy_pool_key, entity);
        log.debug("add -- " + entity.toString() + "  size -- " + RedisUtil.length(proxy_pool_key));
    }

    public static ProxyEntity getProxy() {
        ProxyEntity proxyEntity = RedisUtil.popQueueObj(proxy_pool_key, ProxyEntity.class);
        return proxyEntity;
    }

    public static String createFakeIP() {
        String ret = "";
        int num1 = 10;
        int num2 = (int) (Math.random() * 254 + 1);
        int num3 = (int) (Math.random() * 254 + 1);
        int num4 = (int) (Math.random() * 254 + 1);
        ret = num1 + "." + num2 + "." + num3 + "." + num4;
        return ret;
    }

    public static void main(String[] args){
        System.out.println(createFakeIP());
    }

}
